/**
 * 
 */
package com.net.shop.car.manager.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

/**
 * 切换字view选中状态
 * @author Deve
 * @date 2015-01-17
 */
public class SwitchWidget extends LinearLayout {

	/**
	 * 当前选中位置
	 */
	private int selectedIndex = -1;

	/**
	 * 切换监听
	 * 
	 */
	public interface OnSwitchedListener {
		/**
		 * 当前被选中的位置
		 * 
		 * @param index
		 *            int
		 */
		void onItemSelected(int index);
	}

	/**
	 * @param context
	 *            Context
	 */
	public SwitchWidget(Context context) {
		super(context);
	}

	/**
	 * @param context
	 *            Context
	 * @param attrs
	 *            AttributeSet
	 */
	public SwitchWidget(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	/**
	 * @param context
	 *            Context
	 * @param attrs
	 *            context
	 * @param defStyle
	 *            int
	 */
	public SwitchWidget(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	@Override
	protected void onFinishInflate() {
		// TODO Auto-generated method stub
		super.onFinishInflate();
		if (selectedIndex < 0) {
			setItemSelected(0);
		} else {
			setItemSelected(selectedIndex);
		}
	}

	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	};
	/**
	 * @param onSwitchedListener
	 *            OnSwitchedListener
	 */
	public void setOnSwitchedListener(
			final OnSwitchedListener onSwitchedListener) {
		if (onSwitchedListener == null) {
			return;
		}
		int count = getChildCount();
		for (int i = 0; i < count; i++) {
			final int index = i;
			View view = getChildAt(i);
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					setItemSelected(index);
					onSwitchedListener.onItemSelected(index);
				}
			});
			if (selectedIndex == index) {
				onSwitchedListener.onItemSelected(selectedIndex);
			}
		}
	}

	/**
	 * @param index
	 *            int
	 */
	public void setItemSelected(int index) {
		if (index == selectedIndex) {
			return;
		}
		int count = getChildCount();
		if (selectedIndex >= 0 && selectedIndex < count) {
			View lastSelectView = getChildAt(selectedIndex);
			lastSelectView.setSelected(false);
		}
		if (index >= 0 && index < count) {
			View selecedView = getChildAt(index);
			selecedView.setSelected(true);
			selectedIndex = index;
		}
	}
}
